package cn.xspace.wnx.util;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessageBody;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.EasyUtils;
import com.xspace.android.imcommon.utils.ImPreferences;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.AppUtils;
import com.xspace.android.xafcommon.util.ClassUtil;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.RequestConstant;
import com.xspace.android.xafcommon.util.StringUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import cn.xspace.chatui.bean.ChatFileEntity;
import cn.xspace.chatui.bean.MessageEntity;
import cn.xspace.chatui.bean.MsgRecordEntity;
import cn.xspace.library.bean.Type;
import cn.xspace.library.util.ContentType;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.activity.ChatActivity;
import cn.xspace.wnx.activity.NoticeOrWNXListActivity;
import cn.xspace.wnx.activity.WnxOrgMessageListActivity;
import cn.xspace.wnx.db.ChatRecordDao;
import cn.xspace.wnx.db.MessageRecordDao;
import cn.xspace.wnx.db.MyNewFriendDao;
import cn.xspace.wnx.db.NoticeDao;
import cn.xspace.wnx.db.WNXDBManager;
import cn.xspace.wnx.entity.NewFriendBean;
import cn.xspace.wnx.entity.WNXBean;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by liuchen on 2016/10/12.
 */

public class Notifier {


    private final static String TAG = "notify";
    Ringtone ringtone = null;
    protected final static String[] msg_eng = {"sent a message", "sent a picture", "sent a voice",
            "sent location message", "sent a video", "sent a file", "%1 contacts sent %2 messages"
    };
    protected final static String[] msg_ch = {"发来一条消息", "发来一张图片", "发来一段语音", "发来位置信息", "发来一个视频", "发来一个文件",
            "%1个联系人发来%2条消息"
    };
    protected HashSet<String> fromUsers = new HashSet<String>();
    protected int notificationNum = 0;
    protected static int notifyID = 0525; // start notification id
    protected static int xmppNotifyID = 0526; // start notification
    protected NotificationManager notificationManager = null;
    protected Context appContext;
    protected AudioManager audioManager;
    protected Vibrator vibrator;
    protected String packageName;
    protected String[] msgs;
    protected EaseNotificationInfoProvider notificationInfoProvider;
    //    private LocalBroadcastManager broadcastManager;
    private static Notifier instance;
    private String user_id = "";
    private String user_name = "";
    private boolean isNeedSaveTwoMsg = false;
    private boolean isYouAreInvited = false;
    private boolean isInviteYouOnly = false;
    private long lastNotifiyTime;

    private static List<Integer> notifyIdList = new ArrayList<>();

    /**
     * this function can be override
     *
     * @param context
     * @return
     */
    public Notifier init(Context context) {
        appContext = context;
        notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//        broadcastManager = LocalBroadcastManager.getInstance(appContext);
        packageName = appContext.getApplicationInfo().packageName;
        if (Locale.getDefault().getLanguage().equals("zh")) {
            msgs = msg_ch;
        } else {
            msgs = msg_eng;
        }

        audioManager = (AudioManager) appContext.getSystemService(Context.AUDIO_SERVICE);
        vibrator = (Vibrator) appContext.getSystemService(Context.VIBRATOR_SERVICE);

        user_name = MyInfoUtil.getName(appContext);
        return this;
    }

    public static Notifier getInstance() {
        if (instance == null) {
            instance = new Notifier();
        }
        return instance;
    }

    /**
     * handle the new message
     * this function can be override
     *
     * @param message
     */
    public void onNewMsg(EMMessage message) {
//        if (EMClient.getInstance().chatManager().isSilentMessage(message)) {
//            return;
//        }
        user_id = MyInfoUtil.getMyUserid(appContext);
        LogUtil.d(TAG, message.getChatType() + "");
        if (EMMessage.ChatType.GroupChat == message.getChatType() || EMMessage.ChatType.ChatRoom == message
                .getChatType()) {
            //群聊
            parseChatGroup(message);
        } else if (message.getChatType() == EMMessage.ChatType.Chat) {
            //单聊
            parseChatSingle(message);
        }
    }

//    public void formPushSendNotification(MessageEntity message, boolean isForeground) {
//        sendNotification(message, isForeground, true);
//    }

    protected void sendNotification(final MessageEntity message, final boolean isForeground) {
        playSound(appContext);
        if (!ImPreferences.getInstance(appContext).getPfBoolean(AppUtils.isNotifyOpen)) {
            return;
        }
        String id = "";
        if (message.msg_type == MsgType.CHAT_SINGLE.toNumber()) {
            id = message.msg_sender_id;
        } else if (message.msg_type == MsgType.CHAT_CROUP.toNumber()) {
            id = message.msg_group_id;
        } else if (message.msg_type == (MsgType.NOTICE.toNumber() | MsgType.WNX_MSG
                .toNumber())) {
            id = message.msg_sender_id;
        }
        MessageRecordDao.getInstance().getiMessageData().getMessageEntityByKeyId(id, message.msg_type)
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<MessageEntity>() {
                    @Override
                    public void call(MessageEntity entity) {
                        LogUtil.d("call>>" + (entity == null));

                        if (entity == null || entity.msg_warn_status == MessageEntity.WarnStatus.WARN.toNumber()) {
                            notificationNum++;
                            if (TextUtils.isEmpty(message.msg_group_id)) {
                                fromUsers.add(message.msg_group_id);
                            } else {
                                fromUsers.add(message.msg_sender_id);
                            }

                            sendNotification(message, isForeground, true);
                        }
                    }
                });


    }

//    public void sendNotificationQac(final XmppBean message, final boolean isForeground) {
//        String id = "";
//        String className = XmppUtils.QAC_PLATFORM_ACTIVITY;
//        if (StringUtils.isNull(className)) {
//            return;
//        }
//        Intent mIntent = new Intent(appContext, ClassUtil.getClassByName(className));
//        String platform = message.msgInfo.platForm;
//        if (TextUtils.isEmpty(platform)) {
//            platform = "1";
//        }
//        mIntent.putExtra(
//                ServiceConstant.BR_SERVICE_PUSHMSG_RECEIVED_PLATFORM_KEY,
//                platform);
//        mIntent.putExtra(
//                ServiceConstant.BR_SERVICE_PUSHMSG_RECEIVED_TITLE_KEY,
//                message.body);
//        mIntent.putExtra(
//                ServiceConstant.BR_SERVICE_PUSHMSG_RECEIVED_USERNAME_KEY,
//                message.msgInfo.sendDeptName);
//        mIntent.putExtra(
//                ServiceConstant.BR_SERVICE_PUSHMSG_RECEIVED_USERID_KEY,
//                message.msgInfo.sendDeptId);
//        playSound(appContext);
//        PackageManager packageManager = appContext.getPackageManager();
//        String appname = (String) packageManager.getApplicationLabel(appContext.getApplicationInfo());
//        // notification title
//        String contentTitle = appname;
//        // create and send notificaiton
//        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext)
//                .setSmallIcon(appContext.getApplicationInfo().icon)
//                .setWhen(System.currentTimeMillis())
//                .setAutoCancel(true);
//
//        PendingIntent pendingIntent = PendingIntent.getActivity(appContext, notifyID, mIntent, PendingIntent
//                .FLAG_UPDATE_CURRENT);
//        String content = "";
//        try {
//            JSONObject json = new JSONObject(message.body);
//            content = json.optString("msg_jsonbody");
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        mBuilder.setContentTitle(contentTitle);
//        mBuilder.setTicker(content);
//        mBuilder.setContentText(content);
//        mBuilder.setContentIntent(pendingIntent);
//
//        // mBuilder.setNumber(notificationNum);
//        Notification notification = mBuilder.build();
//        xmppNotifyID++;
//        notificationManager.notify(xmppNotifyID, notification);
//
//    }

    /**
     * set notification info Provider
     *
     * @param provider
     */
    public void setNotificationInfoProvider(EaseNotificationInfoProvider provider) {
        notificationInfoProvider = provider;
    }

    /**
     * send it to notification bar
     * This can be override by subclass to provide customer implementation
     *
     * @param message
     */
    protected void sendNotification(MessageEntity message, boolean isForeground, boolean numIncrease) {
        String username = message.msg_sender_name;
        try {

            String notifyText = username + " ";

            if ((message.msg_type == MsgType.NOTICE.toNumber()) || (message.msg_type == MsgType.WNX_MSG.toNumber())) {
                //微农信或者通知
                notifyText += message.msg_content;

            } else {
                if (message.msg_content_type == ContentType.TXT.toNumber()) {
                    //文本
                    notifyText += msgs[0];
                } else if (message.msg_content_type == ContentType.PICTURE.toNumber()) {
                    notifyText += msgs[1];
                } else if (message.msg_content_type == ContentType.OTHER.toNumber()) {

                } else if (message.msg_content_type == ContentType.VOICE.toNumber()) {
                    notifyText += msgs[2];
                } else if (message.msg_content_type == ContentType.VEDIO.toNumber()) {
                    notifyText += msgs[4];
                } else if (message.msg_content_type == ContentType.LOCATION.toNumber()) {
                    notifyText += msgs[3];
                } else if (message.msg_content_type == ContentType.SYSTEM_WARN.toNumber()) {

                } else if (message.msg_content_type == ContentType.FILE.toNumber()) {
                    notifyText += msgs[5];
                }
            }

            PackageManager packageManager = appContext.getPackageManager();
            String appname = (String) packageManager.getApplicationLabel(appContext.getApplicationInfo());
            // notification title
            String contentTitle = appname;
            if (notificationInfoProvider != null) {
                String customNotifyText = notificationInfoProvider.getDisplayedText(message);
                String customCotentTitle = notificationInfoProvider.getTitle(message);
                if (customNotifyText != null) {
                    notifyText = customNotifyText;
                }

                if (customCotentTitle != null) {
                    contentTitle = customCotentTitle;
                }
            }
            String summaryBody = "";
            if ((message.msg_type == MsgType.NOTICE.toNumber()) || (message.msg_type == MsgType.WNX_MSG.toNumber())) {
                summaryBody = message.msg_content;
            } else {
                int fromUsersNum = fromUsers.size();
                summaryBody = msgs[6].replaceFirst("%1", Integer.toString(fromUsersNum)).replaceFirst("%2", Integer
                        .toString(notificationNum));
            }


            // create and send notificaiton
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext)
                    .setSmallIcon(appContext.getApplicationInfo().icon)
                    .setWhen(System.currentTimeMillis())
                    .setAutoCancel(true);

            Intent msgIntent = appContext.getPackageManager().getLaunchIntentForPackage(packageName);
            if (notificationInfoProvider != null) {
                msgIntent = notificationInfoProvider.getLaunchIntent(message);
            }
            PendingIntent pendingIntent = PendingIntent.getActivity(appContext, notifyID, msgIntent, PendingIntent
                    .FLAG_UPDATE_CURRENT);
//            playSound(appContext);
            mBuilder.setContentTitle(contentTitle);
            mBuilder.setTicker(notifyText);
            mBuilder.setContentText(summaryBody);
            mBuilder.setContentIntent(pendingIntent);
            LogUtil.e(TAG, "wubaojie>>>" + "通知栏信息1" + "contentTitle  " + contentTitle);
            LogUtil.e(TAG, "wubaojie>>>" + "通知栏信息2" + "notifyText  " + notifyText);
            LogUtil.e(TAG, "wubaojie>>>" + "通知栏信息2" + "summaryBody   " + summaryBody);
            // mBuilder.setNumber(notificationNum);
            Notification notification = mBuilder.build();
            if ((message.msg_type == MsgType.NOTICE.toNumber()) || (message.msg_type == MsgType.WNX_MSG.toNumber())) {
                xmppNotifyID++;
                notificationManager.notify(xmppNotifyID, notification);
            } else {
                notificationManager.notify(notifyID, notification);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isChatActivityTop() {
        if (ChatActivity.chatActivity != null && ChatActivity.chatActivity.isVisible) {

            if (listEntity.msg_type == MsgType.CHAT_SINGLE.toNumber() && ChatActivity.getCurrentKeyId()
                    .equals(listEntity.msg_sender_id)) {
                //对应个人会话在前台...
                return true;
            } else if (listEntity.msg_type == MsgType.CHAT_CROUP.toNumber() && ChatActivity
                    .getCurrentKeyId().equals(listEntity.msg_group_id)) {
                //对应群主会话在前台...
                return true;
            } else if (listEntity.msg_type == MsgType.CHAT_QAC_FORM.toNumber() && ChatActivity.getCurrentKeyId()
                    .equals(recordEntity.msg_sender_id) && recordEntity.form_id != null && recordEntity.form_id
                    .equals(ChatActivity.formId)) {
                return true;
            }
        }
        return false;
    }

    private boolean isQacChatActivityTop() {
        if (ChatActivity.chatActivity != null && ChatActivity.chatActivity.isVisible) {

            if (listEntity.msg_type == MsgType.CHAT_SINGLE.toNumber() && ChatActivity.getCurrentKeyId()
                    .equals(listEntity.msg_sender_id)) {
                //对应个人会话在前台...
                return true;
            } else if (listEntity.msg_type == MsgType.CHAT_CROUP.toNumber() && ChatActivity
                    .getCurrentKeyId().equals(listEntity.msg_group_id)) {
                //对应群主会话在前台...
                return true;
            }
        }
        return false;
    }

    private boolean isXmppTop(MessageEntity messgeEntity) {
        if (messgeEntity.msg_type == MsgType.WNX_MSG.toNumber()) {
            if (WnxOrgMessageListActivity.isActivityAlive()) {
                messgeEntity.isRead = true;
                return true;
            }
        }
        return false;
    }

    private void saveDb() {
        if (isChatActivityTop() || recordEntity.msg_type == ContentType.SYSTEM_WARN.toNumber()) {
            //对应聊天界面在前台或者 群组系统提示操作不作为未读标志
            if (recordEntity.msg_type != MsgType.CHAT_QAC_FORM.toNumber()) {
                listEntity.isRead = true;
            } else {
                recordEntity.isRead = true;
            }
        }

        if (recordEntity.msg_type != MsgType.CHAT_QAC_FORM.toNumber()) {

            MessageRecordDao.getInstance().getiMessageData().updateMessageList(listEntity)
                    .observeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<String>() {
                        @Override
                        public void call(String s) {
                            Map<String, Object> messageMap = new HashMap<>();
                            messageMap.put(EventBusConstant.TYPE, EventBusConstant.HUANXIN_PUSH);
                            messageMap.put(EventBusConstant.HUANXIN_PUSH_BEAN, listEntity);
                            messageMap.put(EventBusConstant.TIME_PUSH_BEAN, System.currentTimeMillis());
                            EventBus.getDefault().post(messageMap);
                        }
                    });

        }
        if (recordEntity.msg_content_type == ContentType.SYSTEM_WARN.toNumber() && recordEntity
                .tip_type == MessageEntity.SystemType.WithDraw.toNumber()) {
            //撤销消息，删除对用记录
            ChatRecordDao.getInstance().getIChatRecordOperation().deleteOneChatRecordByInserMsgId(recordEntity.msg_id)
                    .subscribeOn(Schedulers.io())
                    .subscribe(new Action1<Integer>() {
                        @Override
                        public void call(Integer integer) {
//                            Map<String, Object> chatMap = new HashMap<>();
//                            chatMap.put(EventBusConstant.TYPE, EventBusConstant.HUANXIN_PUSH);
//                            chatMap.put(EventBusConstant.HUANXIN_PUSH_BEAN, recordEntity);
//                            EventBus.getDefault().post(chatMap);
                        }
                    });
        }
        ChatRecordDao.getInstance().getIChatRecordOperation().insertMsgRecord(recordEntity)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        LogUtil.d(TAG, "聊天记录插入成功" + s);
                        Map<String, Object> chatMap = new HashMap<>();
                        chatMap.put(EventBusConstant.TYPE, EventBusConstant.HUANXIN_PUSH);
                        chatMap.put(EventBusConstant.HUANXIN_PUSH_BEAN, recordEntity);
                        chatMap.put(EventBusConstant.TIME_PUSH_BEAN, System.currentTimeMillis());
                        EventBus.getDefault().post(chatMap);

                    }
                });
//        if (recordSystemEntity != null && isNeedSaveTwoMsg) {
//            if (isInviteYouOnly) {
//                isInviteYouOnly = false;
//            } else {
//                ChatRecordDao.getInstance().getIChatRecordOperation().insertMsgRecord(recordSystemEntity)
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(new Action1<String>() {
//                            @Override
//                            public void call(String s) {
//                                LogUtil.d(s);
//                                LogUtil.d(TAG, "系统通知  插入成功" + s);
//                                if (isNeedSaveTwoMsg && recordSystemEntity != null) {
//                                    Map<String, Object> chat2Map = new HashMap<>();
//                                    chat2Map.put(EventBusConstant.TYPE, EventBusConstant.HUANXIN_PUSH);
//                                    chat2Map.put(EventBusConstant.HUANXIN_PUSH_BEAN, recordSystemEntity);
//                                    chat2Map.put(EventBusConstant.TIME_PUSH_BEAN, System.currentTimeMillis());
//                                    EventBus.getDefault().post(chat2Map);
//                                }
//                                isNeedSaveTwoMsg = false;
//                            }
//                        });
//            }
//        }
    }

    //针对系统消息
    private boolean isSystemNotice() {
        if (listEntity.msg_content_type == ContentType.SYSTEM_WARN.toNumber()) {
            LogUtil.d("系统消息不通知-------------》》》》");
            return true;
        } else {
            return false;
        }
    }

    public void dealXmppNotice(final MessageEntity messageEntity, final WNXBean wnxBean) {
        //通知栏广播
        if (!EasyUtils.isAppRunningForeground(appContext)) {
            EMLog.d(TAG, "app is running in backgroud");
            sendNotification(messageEntity, false, false);
        } else {
            String topActivity = EasyUtils.getTopActivityName(appContext);
            LogUtil.d(TAG, topActivity);
            LogUtil.d(TAG, NoticeOrWNXListActivity.TAG);
            if (!isXmppTop(messageEntity)) {
                LogUtil.d("!isXmppTop(messageEntity)");
                wnxBean.unreadCount = 1;
                sendNotification(messageEntity, false, false);
            } else {
                LogUtil.d("isXmppTop(messageEntity)");
                messageEntity.isRead = true;
                wnxBean.unreadCount = 0;
            }
        }
        //Ui更新13553152203
//        Map<String, Object> chatMap = new HashMap<>();
//        chatMap.put(EventBusConstant.TYPE, EventBusConstant.HUANXIN_PUSH);
//        chatMap.put(EventBusConstant.HUANXIN_PUSH_BEAN, messageEntity);
//        EventBus.getDefault().post(chatMap);


        MessageRecordDao.getInstance().getiMessageData().updateMessageList(messageEntity)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        LogUtil.d(s);
                        Map inParam = new HashMap();
                        inParam.put(EventBusConstant.HUANXIN_PUSH_BEAN, messageEntity);
                        inParam.put(EventBusConstant.TYPE, EventBusConstant.HUANXIN_PUSH);
                        EventBus.getDefault().post(inParam);
                        Map wnxParam = new HashMap();
                        wnxParam.put(EventBusConstant.XMPP_PUSH_BEAN, wnxBean);
                        wnxParam.put(EventBusConstant.TYPE, EventBusConstant.XMPP_PUSH);
                        EventBus.getDefault().post(wnxParam);
                    }
                });
        NoticeDao.getInstance().getData().insertWnxNotice(wnxBean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        //清楚空白的数据
                        WNXDBManager.getInstance().deleleBlankWnx(wnxBean.msg_sender_id);
                    }
                })
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        LogUtil.d(s);
                        //发送通知消息
                    }
                });
    }

    public boolean isNeedNotice = true;


    private void dealHuanxinNotice() {
        LogUtil.d("dealHuanxinNotice : isNeedNotice :" + isNeedNotice);


//        if (isNeedNotice) {
//            Map<String, Object> chatMap = new HashMap<>();
//            chatMap.put(EventBusConstant.TYPE, EventBusConstant.HUANXIN_PUSH);
//            chatMap.put(EventBusConstant.HUANXIN_PUSH_BEAN, recordEntity);
//            EventBus.getDefault().post(chatMap);
//
//            if (isNeedSaveTwoMsg && recordSystemEntity != null) {
//                Map<String, Object> chat2Map = new HashMap<>();
//                chatMap.put(EventBusConstant.TYPE, EventBusConstant.HUANXIN_PUSH);
//                chatMap.put(EventBusConstant.HUANXIN_PUSH_BEAN, recordSystemEntity);
//                EventBus.getDefault().post(chat2Map);
//            }
//
//        } else {
//            isNeedNotice = true;
//        }

        if (!EasyUtils.isAppRunningForeground(appContext)) {
            EMLog.d(TAG, "app is running in backgroud");
            if (!isSystemNotice())
                sendNotification(listEntity, false);
        } else {
            String topActivity = EasyUtils.getTopActivityName(appContext);
            LogUtil.d(TAG, topActivity);
            LogUtil.d(TAG, ChatActivity.TAG);
//            if (!topActivity.contains(ChatActivity.TAG)) {
//                sendNotification(listEntity, true);
//            } else {
            //聊天界面
            if (!isSystemNotice()) { //系统通知不提醒
                if (isChatActivityTop()) {
                    playSound(appContext);//对应会话在前台...
                } else {
                    sendNotification(listEntity, true);
                }
            }
//            if (isChatActivityTop()) {
//                if (!isSystemNotice()) //系统通知不提醒
//                    //对应会话在前台...
//                    playSound(appContext);
//            } else {
//                if (!isSystemNotice())
//                    sendNotification(listEntity, true);
//            }
        }
    }

//    private boolean isShowNoticeForQac() {
//        if (!EasyUtils.isAppRunningForeground(appContext)) {
//            EMLog.d(TAG, "app is running in backgroud");
//            return true;
//
//        } else {
//            String topActivity = EasyUtils.getTopActivityName(appContext);
//            LogUtil.d(TAG, topActivity);
//            LogUtil.d(TAG, "QacChatConversationActivity");
//            if (topActivity.equals("QacChatConversationActivity")) {
//
//            }
//            //聊天界面
//        }
//    }


    /**
     * 解析单聊
     *
     * @param message
     */
    public void parseChatSingle(EMMessage message) {
        EMMessageBody body = message.getBody();
        String bodyStr = body.toString();
        LogUtil.d(TAG, "body str " + bodyStr);
        String jsondata = "";
        if (bodyStr.indexOf("txt:") == 0) {
            jsondata = bodyStr.substring(5);
            jsondata = jsondata.substring(0, jsondata.lastIndexOf("\""));
        }
        JSONObject jsob;
        try {
            jsob = new JSONObject(jsondata);
            //区分推送平台
            String platForm = jsob.optString("plat_form");
            //区分单聊还是推送push
            String msg_plat = jsob.optString("msg_plat");
            if ("QACWEB".equals(platForm)) { //农技员推送
                if ("qac_chat_single".equals(msg_plat)) {
                    parseQacPush(jsob);
                }
//                else if ("qac_chat_group".equals(msg_plat)) {
//                    parseQacChatGroup(jsob);
//                }
            } else if ("WNXWEB".equals(platForm)) { //微农信
                if ("wnx_inviate".equals(msg_plat)) { //是推送过来的加好友信息
                    parseInvite(jsob);
                } else if ("wnx_delfirend".equals(msg_plat)) { //推送过来的删除好友信息
                    parseDelFriend(jsob);
                } else if ("wnx_information".equals(msg_plat)) { //微农信或者通知公告推送
                    parseWnxInfo(jsob);
                } else if ("wnx_chat_single".equals(msg_plat)) {
                    parseWnxChatSingle(jsob);
                }
            } else if ("WORK".equals(platForm)) { //工作日志评论推送
                if ("work_chat_single".equals(msg_plat)) {
                    parseWorkChatSingle(jsob);
                } else if ("work_log_comment".equals(msg_plat)) {
                    LogCommentPush(jsob);
                } else if ("work_log_declare".equals(msg_plat)) {
                    DeclarePush(jsob);
                }
            } else {
                LogUtil.d(TAG, "wubaojie>>>parseChatSingle: 接受到了未知的模块数据");
            }
//
//            String msg_sender_id = "";
//            String msg_id = "";
//            String msg_time = "";
//            String msg_sender_logo = "";
//            String msg_txt = "";
//            String msg_sender_name = "";
//            String msg_recevier_id = "";
//            int msg_dutime = 0;
//            String msg_postion = "";
//            String msg_lng = "";
//            String msg_lat = "";
//            String msg_name = "";
//            int msg_type = 0;
//
//            if ("LOGWEB".equals(platForm)) {
//                JSONObject jsonProData = jsob.optJSONObject("proData");
//                String jsonMsgBody = jsonProData.optString("msg_jsonbody");
//                JSONObject jsonPro = new JSONObject(jsonMsgBody);
//                msg_sender_id = jsonPro.optString("sender_id");
//                msg_id = jsonPro.optString("msg_id");
//                msg_time = jsonPro.optString("msg_ctime");
//                msg_sender_name = jsonPro.optString("sender_name");
//                msg_sender_logo = jsonPro.optString("sender_logo");
//                msg_txt = jsonPro.optString("msg_text");
//                msg_type = jsonPro.optInt("msg_type");
//                msg_recevier_id = jsonPro.optString("receiver_id");
//                msg_dutime = jsonPro.optInt("msg_dutime");
//                msg_name = jsonPro.optString("msg_name");
//
//                msg_postion = jsonPro.optString("msg_postion");
//                msg_lat = jsonPro.optString("msg_lat");
//                msg_lng = jsonPro.optString("msg_lng");
//                //解析form相关
//                String formId = jsonPro.optString("form_id");
//                recordEntity.form_id = formId;
//                listEntity.form_id = formId;
//                int form_type = jsonPro.optInt("form_type");
//                recordEntity.form_type = form_type;
//                listEntity.form_type = form_type;
//
//                String form_url = jsonPro.optString("form_url");
//                int work_isdone = jsonPro.optInt("work_isdone");
//                recordEntity.form_url = form_url;
//                listEntity.form_url = form_url;
//                //用于记录申报单的状态
//                recordEntity.form_status = Type.getWorkItemStatusServer(work_isdone + "");
//                listEntity.form_status = Type.getWorkItemStatusServer(work_isdone + "");
//                recordEntity.msg_type = MsgType.CHAT_QAC_FORM.toNumber();
//                listEntity.msg_type = MsgType.CHAT_QAC_FORM.toNumber();
//            } else {
//                msg_sender_id = jsob.optString("msg_sender_id");
//                msg_id = jsob.optString("msg_id");
//                msg_time = jsob.optString("msg_time");
//                msg_sender_name = jsob.optString("msg_sender_name");
//                msg_sender_logo = jsob.optString("msg_sender_logo");
//                msg_txt = jsob.optString("msg_text");
//                msg_type = jsob.optInt("msg_type");
//                msg_recevier_id = jsob.optString("msg_recevier_id");
//                msg_postion = jsob.optString("msg_postion");
//                msg_lat = jsob.optString("msg_lat");
//                msg_lng = jsob.optString("msg_lng");
//                msg_dutime = jsob.optInt("msg_dutime");
//                msg_name = jsob.optString("msg_name");
//                recordEntity.msg_type = MsgType.CHAT_SINGLE.toNumber();
//                listEntity.msg_type = MsgType.CHAT_SINGLE.toNumber();
//            }
//            int tip_type = jsob.optInt("tip_type");
//            String msg_sender_sex = jsob.optString("msg_sender_sex");
//            String msg_recevier_name = jsob.optString("msg_recevier_name");
//            String msg_recevier_logo = jsob.optString("msg_recevier_logo");
//            String inserttime = System.currentTimeMillis() + "";
//
//            listEntity.msg_content = ChatFileEntity.getContentByType(msg_txt, msg_type);
//
////            if (msg_type == MessageEntity.ContentType.OTHER.toNumber()) {
////                return MessageEntity.ContentType.OTHER.getTxt();
//            recordEntity.msg_content = msg_txt;
////            } else {
////                recordEntity.msg_content = showContent;
////            }
//
//            //检查是否包含附件
//            if (ChatFileEntity.isNeedSaveFile(msg_type)) {
//                ChatFileEntity fileEntity = new ChatFileEntity();
//                //文件实体类url
////                fileEntity.msg_id = msg_id;
//                fileEntity.file_url_remote = msg_txt;
//                fileEntity.file_type = msg_type;
//                if (msg_type == ContentType.VOICE.toNumber()) {
//                    fileEntity.msg_dutime = msg_dutime;
//                } else if (msg_type == ContentType.LOCATION.toNumber()) {
//                    fileEntity.address_desc = msg_postion;
//                    fileEntity.lat = msg_lat;
//                    fileEntity.lng = msg_lng;
//                } else if (msg_type == ContentType.FILE.toNumber()) {
//                    fileEntity.file_name = msg_name;
//                }
//                recordEntity.mFileEntity = fileEntity;
//            }
//            //给列表赋值
//            listEntity.inserttime = inserttime;
//            listEntity.msg_sender_id = msg_sender_id;
//            listEntity.msg_sender_name = msg_sender_name;
//            listEntity.msg_logo = msg_sender_logo;
//            listEntity.msg_content_type = msg_type;
//            listEntity.tip_type = tip_type;
//            listEntity.msg_receiver_id = msg_recevier_id;
//            listEntity.msg_receiver_name = msg_recevier_name;
//
//            listEntity.msg_last_time = msg_time;
//
//            //聊天记录beana操作
//            recordEntity.msg_id = msg_id;
//            recordEntity.msg_sender_id = msg_sender_id;
//            recordEntity.inserttime = inserttime;
//            recordEntity.msg_sender_name = msg_sender_name;
//            recordEntity.msg_logo = msg_sender_logo;
//            recordEntity.msg_content_type = msg_type;
//            recordEntity.tip_type = tip_type;
//            recordEntity.msg_receiver_id = msg_recevier_id;
//            recordEntity.msg_receiver_name = msg_recevier_name;
//            recordEntity.msg_last_time = msg_time;
//
////            recordEntity.user_sex = msg_sender_sex;
////            listEntity.user_sex = msg_sender_sex;
//
//            LogUtil.d(TAG, "enrity " + listEntity.toString());
//            LogUtil.d(TAG, "recordEntity " + recordEntity.toString());
//            //保存数据库
////            MessageRecordDao.getInstance().updateMessageList(listEntity);
//
////            ChatRecordDao.getInstance().insertMsgRecord(recordEntity);
//            saveDb();
//            dealHuanxinNotice();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void parseQacChatGroup(JSONObject jsobPre) throws JSONException {
        JSONObject jsonPro = jsobPre.optJSONObject("pro_data");
        String jsonMsgBody = jsonPro.optString("msg_jsonbody");
        JSONObject jsob = new JSONObject(jsonMsgBody);
        //农技员群聊推送
        String userId = jsob.optString("user_id");
        String senderId = jsob.optString("msg_sender_id");
        //操作类型
        int tip_type = jsob.optInt("tip_type");
        //发送内容描述
        String msg_txt = jsob.optString("msg_text");
        //群组Id
        String group_id = jsob.optString("group_id");
        if (user_id.equals(userId)) { //沃基己发的
            return;
        }
        if (user_id.equals(senderId)) {
            return;
        }
        if (tip_type == 1) {
            //转呈添加人员
            msg_txt = "您有问题需要会商";
        }
        Map<String, Object> pushMap = new HashMap<>();
        pushMap.put(EventBusConstant.TYPE, EventBusConstant.QAC_CHAT_TRANSFER);
        pushMap.put(EventBusConstant.ACTION_VALUE, jsob);
        EventBus.getDefault().post(pushMap);

        String className = ClassUtil.QAC_CHAT_ACTIVITY;
        if (StringUtils.isNull(className)) {
            return;
        }
        String qu_id_push = jsob.optString("qu_id");
        Intent mIntent = new Intent(appContext, ClassUtil.getClassByName(className));
        mIntent.putExtra("qu_id", qu_id_push);
        mIntent.putExtra("group_id", group_id);
        mIntent.putExtra(Constants.QUESTION_TYPE, Constants.TRANSFER);
        playSound(appContext);
        PackageManager packageManager = appContext.getPackageManager();
        String appname = (String) packageManager.getApplicationLabel(appContext.getApplicationInfo());
        // notification title
        // create and send notificaiton
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext)
                .setSmallIcon(appContext.getApplicationInfo().icon)
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true);
        PendingIntent pendingIntent = PendingIntent.getActivity(appContext, notifyID, mIntent, PendingIntent
                .FLAG_UPDATE_CURRENT);
        mBuilder.setContentTitle(appname);
        mBuilder.setTicker(msg_txt);
        mBuilder.setContentText(msg_txt);
        mBuilder.setContentIntent(pendingIntent);
        // mBuilder.setNumber(notificationNum);
        Notification notification = mBuilder.build();
        xmppNotifyID++;
        notifyIdList.add(xmppNotifyID);
        notificationManager.notify(xmppNotifyID, notification);
    }

    private void parseWorkChatSingle(JSONObject jsob) throws JSONException {
        JSONObject jsonPro = jsob.optJSONObject("pro_data");
        String jsonMsgBody = jsonPro.optString("msg_jsonbody");
        JSONObject jsonObject = new JSONObject(jsonMsgBody);

        listEntity = new MessageEntity();
        recordEntity = new MsgRecordEntity();

        String msg_sender_id = jsonObject.optString("sender_id");
        String msg_id = jsonObject.optString("msg_id");
        String msg_time = jsonObject.optString("msg_ctime");
        String msg_sender_name = jsonObject.optString("sender_name");
        String msg_sender_logo = jsonObject.optString("sender_logo");
        String msg_txt = jsonObject.optString("msg_text");
        int msg_type = jsonObject.optInt("msg_type");
        String msg_recevier_id = jsonObject.optString("receiver_id");
        int msg_dutime = jsonObject.optInt("msg_dutime");
        String msg_name = jsonObject.optString("msg_name");
        String msg_postion = jsonObject.optString("msg_postion");
        String msg_lat = jsonObject.optString("msg_lat");
        String msg_lng = jsonObject.optString("msg_lng");
        //解析form相关
        String formId = jsonObject.optString("form_id");
        String formName = jsonObject.optString("form_name");
        recordEntity.form_id = formId;
        listEntity.form_id = formId;
        listEntity.form_name = formName;
        int form_type = jsonObject.optInt("form_type");
        recordEntity.form_type = form_type;
        listEntity.form_type = form_type;
        String form_url = jsonObject.optString("form_url");
        int work_isdone = jsonObject.optInt("work_isdone");
        recordEntity.form_url = form_url;
        listEntity.form_url = form_url;
        //用于记录申报单的状态
        recordEntity.form_status = Type.getWorkItemStatusServer(work_isdone + "");
        listEntity.form_status = Type.getWorkItemStatusServer(work_isdone + "");
        recordEntity.msg_type = MsgType.CHAT_QAC_FORM.toNumber();
        listEntity.msg_type = MsgType.CHAT_QAC_FORM.toNumber();
        int tip_type = jsonObject.optInt("tip_type");
        String msg_sender_sex = jsonObject.optString("msg_sender_sex");
        String msg_recevier_name = jsonObject.optString("msg_recevier_name");
        String msg_recevier_logo = jsonObject.optString("msg_recevier_logo");
        String inserttime = System.currentTimeMillis() + "";

        listEntity.msg_content = ChatFileEntity.getContentByType(msg_txt, msg_type);

        recordEntity.msg_content = msg_txt;

        //检查是否包含附件
        if (ChatFileEntity.isNeedSaveFile(msg_type)) {
            ChatFileEntity fileEntity = new ChatFileEntity();
            //文件实体类url
//                fileEntity.msg_id = msg_id;
            fileEntity.file_url_remote = msg_txt;
            fileEntity.file_type = msg_type;
            if (msg_type == ContentType.VOICE.toNumber()) {
                fileEntity.msg_dutime = msg_dutime;
            } else if (msg_type == ContentType.LOCATION.toNumber()) {
                fileEntity.address_desc = msg_postion;
                fileEntity.lat = msg_lat;
                fileEntity.lng = msg_lng;
            } else if (msg_type == ContentType.FILE.toNumber()) {
                fileEntity.file_name = msg_name;
            }
            recordEntity.mFileEntity = fileEntity;
        }
        //给列表赋值
        listEntity.inserttime = inserttime;
        listEntity.msg_sender_id = msg_sender_id;
        listEntity.msg_sender_name = msg_sender_name;
        listEntity.msg_logo = msg_sender_logo;
        listEntity.msg_content_type = msg_type;
        listEntity.tip_type = tip_type;
        listEntity.msg_receiver_id = msg_recevier_id;
        listEntity.msg_receiver_name = msg_recevier_name;

        listEntity.msg_last_time = msg_time;

        //聊天记录beana操作
        recordEntity.msg_id = msg_id;
        recordEntity.msg_sender_id = msg_sender_id;
        recordEntity.inserttime = inserttime;
        recordEntity.msg_sender_name = msg_sender_name;
        recordEntity.msg_logo = msg_sender_logo;
        recordEntity.msg_content_type = msg_type;
        recordEntity.tip_type = tip_type;
        recordEntity.msg_receiver_id = msg_recevier_id;
        recordEntity.msg_receiver_name = msg_recevier_name;
        recordEntity.msg_last_time = msg_time;

//            recordEntity.user_sex = msg_sender_sex;
//            listEntity.user_sex = msg_sender_sex;

        LogUtil.d(TAG, "enrity " + listEntity.toString());
        LogUtil.d(TAG, "recordEntity " + recordEntity.toString());
        //保存数据库
        saveDb();
        dealWorkChatSingleNotice();
    }

    private void dealWorkChatSingleNotice() {
        if (!EasyUtils.isAppRunningForeground(appContext)) {
            if (!isSystemNotice())
                sendNotification(listEntity, false);
        } else {
            String topActivity = EasyUtils.getTopActivityName(appContext);
            LogUtil.d(TAG, topActivity);
            LogUtil.d(TAG, ChatActivity.TAG);
            //聊天界面
            if (!isSystemNotice()) { //系统通知不提醒
                if (isChatActivityTop()) {
                    playSound(appContext);//对应会话在前台...
                } else {
                    sendNotification(listEntity, true);
                }
            }
        }
    }
    // 申报单发生变化
    private void DeclarePush(JSONObject jsob) {
        try {
            String pro_data = jsob.optString("pro_data");
            JSONObject jsonPro = new JSONObject(pro_data);
            String jsonMsgBody = jsonPro.optString("msg_jsonbody");
            Intent intent = new Intent();
            intent.putExtra("msg_jsonbody", jsonMsgBody);
            intent.setAction("cn.xspace.module.mywork.DeclarePushReceiver");//此处的名字要和接受者的一致
            appContext.sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void LogCommentPush(JSONObject jsob) throws JSONException {
        JSONObject jsonPro = jsob.optJSONObject("pro_data");
//        String pro_data = jsob.optString("pro_data");
//        JSONObject jsonPro = new JSONObject(pro_data);
        String msg_id = jsonPro.optString("msg_id"); //解析pro_data中的msg_id
        sendReceipt(msg_id); //发送回执
        String jsonMsgBody = jsonPro.optString("msg_jsonbody");
        Intent intent = new Intent();
        intent.putExtra("msg_jsonbody", jsonMsgBody);
        intent.setAction("cn.xspace.module.mywork.HuanXinPushReceiver");//此处的名字要和接受者的一致
        appContext.sendBroadcast(intent);
        playSound(appContext);
        JSONObject jsonObject = new JSONObject(jsonMsgBody);
        String reviewer_name = jsonObject.optString("sender_name");
        String receiver_id = jsonObject.optString("receiver_id");
        String receiver_name = jsonObject.optString("receiver_name");
        Intent mIntent = new Intent(appContext, ClassUtil.getClassByName(ClassUtil.LogCommitActivity));
        String msg_body = reviewer_name;
        String string;
        if (user_id.equals(receiver_id)) {//是我自己,别人评论我
            string = "你的"; //你的
        } else {
            string = receiver_name; //别人的
        }
        //评论的谁
        msg_body += String.format("评论了%s日志", string);
        sendNotification(msg_body, mIntent);
    }

    /**
     * 处理微农信单聊
     *
     * @param jsob
     * @throws JSONException
     */
    private void parseWnxChatSingle(JSONObject jsob) throws JSONException {
        JSONObject jsonPro = jsob.optJSONObject("pro_data");
        String jsonMsgBody = jsonPro.optString("msg_jsonbody");
        JSONObject jsonObject = new JSONObject(jsonMsgBody);

        listEntity = new MessageEntity();
        recordEntity = new MsgRecordEntity();
        String msg_sender_id = jsonObject.optString("msg_sender_id");
        String msg_id = jsonObject.optString("msg_id");
        String msg_time = jsonObject.optString("msg_time");
        String msg_sender_name = jsonObject.optString("msg_sender_name");
        String msg_sender_logo = jsonObject.optString("msg_sender_logo");
        String msg_txt = jsonObject.optString("msg_text");
        int msg_type = jsonObject.optInt("msg_type");
        String msg_recevier_id = jsonObject.optString("msg_recevier_id");
        String msg_postion = jsonObject.optString("msg_postion");
        String msg_lat = jsonObject.optString("msg_lat");
        String msg_lng = jsonObject.optString("msg_lng");
        int msg_dutime = jsonObject.optInt("msg_dutime");
        String msg_name = jsonObject.optString("msg_name");
        String msg_sender_sex = jsonObject.optString("msg_sender_sex");
        String msg_recevier_name = jsonObject.optString("msg_recevier_name");
        String msg_recevier_logo = jsonObject.optString("msg_recevier_logo");
        String inserttime = System.currentTimeMillis() + "";
        int tip_type = jsonObject.optInt("tip_type");

        recordEntity.msg_type = MsgType.CHAT_SINGLE.toNumber();
        listEntity.msg_type = MsgType.CHAT_SINGLE.toNumber();

        listEntity.msg_content = ChatFileEntity.getContentByType(msg_txt, msg_type);
        recordEntity.msg_content = msg_txt;

        //检查是否包含附件
        if (ChatFileEntity.isNeedSaveFile(msg_type)) {
            ChatFileEntity fileEntity = new ChatFileEntity();
            //文件实体类url
//                fileEntity.msg_id = msg_id;
            fileEntity.file_url_remote = msg_txt;
            fileEntity.file_type = msg_type;
            if (msg_type == ContentType.VOICE.toNumber()) {
                fileEntity.msg_dutime = msg_dutime;
            } else if (msg_type == ContentType.LOCATION.toNumber()) {
                fileEntity.address_desc = msg_postion;
                fileEntity.lat = msg_lat;
                fileEntity.lng = msg_lng;
            } else if (msg_type == ContentType.FILE.toNumber()) {
                fileEntity.file_name = msg_name;
            }
            recordEntity.mFileEntity = fileEntity;
        }
        //给列表赋值
        listEntity.inserttime = inserttime;
        listEntity.msg_sender_id = msg_sender_id;
        listEntity.msg_sender_name = msg_sender_name;
        listEntity.msg_logo = msg_sender_logo;
        listEntity.msg_content_type = msg_type;
        listEntity.tip_type = tip_type;
        listEntity.msg_receiver_id = msg_recevier_id;
        listEntity.msg_receiver_name = msg_recevier_name;

        listEntity.msg_last_time = msg_time;

        //聊天记录beana操作
        recordEntity.msg_id = msg_id;
        recordEntity.msg_sender_id = msg_sender_id;
        recordEntity.inserttime = inserttime;
        recordEntity.msg_sender_name = msg_sender_name;
        recordEntity.msg_logo = msg_sender_logo;
        recordEntity.msg_content_type = msg_type;
        recordEntity.tip_type = tip_type;
        recordEntity.msg_receiver_id = msg_recevier_id;
        recordEntity.msg_receiver_name = msg_recevier_name;
        recordEntity.msg_last_time = msg_time;

//            recordEntity.user_sex = msg_sender_sex;
//            listEntity.user_sex = msg_sender_sex;

        LogUtil.d(TAG, "enrity " + listEntity.toString());
        LogUtil.d(TAG, "recordEntity " + recordEntity.toString());
        //保存数据库
        saveDb();
        dealHuanxinNotice();
    }

    /**
     * 处理微农信和通知公告推送
     *
     * @param jsob
     * @throws JSONException
     */
    private void parseWnxInfo(JSONObject jsob) throws JSONException {
        String sendTime = jsob.optString("send_time");
        String pro_data = jsob.optString("pro_data");
        JSONObject jsonPro = new JSONObject(pro_data);
//                    JSONObject jsonPro = jsob.optJSONObject("pro_data");
        LogUtil.d(TAG, "wubaojie>>>parseChatSingle: pro_data:" + pro_data + "jsonPro:" + jsonPro);
        String biz_cod = jsonPro.optString("biz_code");//通知公告01 /微农资讯 02
        String logo = jsonPro.optString("logo");
        String dept_id = jsonPro.optString("dept_id");
        String dept_name = jsonPro.optString("dept_name");
        String msg_id = jsonPro.optString("msg_id");
        String msg_type = jsonPro.optString("msg_type");
        String msg_sequenceId = jsonPro.optString("msg_sequenceId");
        LogUtil.d(TAG, "wubaojie>>>parseChatSingle: 微农信或者通知公告:" + msg_id);
        if (WNXDBManager.getInstance().isNoticeWnxExist(msg_id)) {
            LogUtil.e(TAG, "wubaojie>>>WnxPush: 已存在该条推送通知" + msg_id);
            return;
        }

        final MessageEntity messageEntity = new MessageEntity();
        final WNXBean wnxBean = new WNXBean();
        if (biz_cod.equalsIgnoreCase("02")) {//微农资讯
            messageEntity.msg_type = MsgType.WNX_MSG.toNumber();
            wnxBean.msg_type = MsgType.WNX_MSG.toNumber();
        } else if (biz_cod.equalsIgnoreCase("01")) {//通知公告
            messageEntity.msg_type = MsgType.NOTICE.toNumber();
            wnxBean.msg_type = MsgType.NOTICE.toNumber();
        }
        wnxBean.msg_logo = logo;
        messageEntity.msg_sender_id = dept_id;
        wnxBean.msg_sender_id = dept_id;
        messageEntity.msg_sender_name = dept_name;
        wnxBean.msg_sender_name = dept_name;

        messageEntity.msg_last_time = sendTime;
        wnxBean.msg_send_time = sendTime;
//            messageEntity.msg_last_time = DateUtils.StringToString(null, sendTime);
//            wnxBean.msg_send_time = DateUtils.StringToString(null, sendTime);
        messageEntity.msg_content_type = ContentType.TXT.toNumber();
        wnxBean.msg_content_type = ContentType.TXT.toNumber();

        String msg_jsonbody = jsonPro.optString("msg_jsonbody");
        JSONObject jsonBody = new JSONObject(msg_jsonbody);
//                    JSONObject jsonBody = jsonPro.optJSONObject("msg_jsonbody");
        JSONArray newsArray = jsonBody.optJSONArray("newssnap");
        if (newsArray.length() > 0) {
            String firstTitle = newsArray.getJSONObject(0).optString("title");
            wnxBean.msg_title = firstTitle;
            messageEntity.msg_content = messageEntity.msg_sender_name + " ：" + firstTitle;
        } else {
            messageEntity.msg_content = messageEntity.msg_sender_name + " ：-----";
            wnxBean.msg_title = " -----";
        }
        wnxBean.msg_kind = msg_type;
        wnxBean.content = newsArray.toString();
        wnxBean.msg_id = msg_id;

        LogUtil.d(messageEntity.toString());
        LogUtil.d(wnxBean.toString());
        Notifier.getInstance().dealXmppNotice(messageEntity, wnxBean);
        sendReceipt(msg_id);
    }

    private void parseDelFriend(JSONObject jsob) throws JSONException {
        JSONObject jsonPro = jsob.optJSONObject("pro_data");
        String jsonMsgBody = jsonPro.optString("msg_jsonbody");
        JSONObject jsonObject = new JSONObject(jsonMsgBody);
        final NewFriendBean bean = new NewFriendBean();
        bean.add_status = jsonObject.optInt("add_status");
        bean.user_id = jsonObject.optString("user_id"); //发送人的id
        bean.user_logo = jsonObject.optString("user_logo");
        bean.user_name = jsonObject.optString("user_name");
        bean.friend_id = jsonObject.optString("friend_id"); //要加的人的id,即本人id
        bean.friend_logo = jsonObject.optString("friend_logo");
        bean.friend_name = jsonObject.optString("friend_name");
        bean.req_desc = jsonObject.optString("req_desc");
        ChatRecordDao.getInstance().getIChatRecordOperation().clearChatRecord(bean.user_id,
                MsgType.CHAT_SINGLE.toNumber())
                .subscribeOn(Schedulers.io())
                .doOnNext(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        MessageRecordDao.getInstance().deleteSingleChat(bean.user_id);
                    }
                })
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        Map<String, Object> datamap = new HashMap<>();
                        datamap.put(EventBusConstant.TYPE, EventBusConstant.DELETE_FRIEND_PUSH);
                        datamap.put(EventBusConstant.ACTION_KEY, EventBusConstant.DELETE_FRIEND_FINISH);
                        datamap.put(EventBusConstant.ACTION_VALUE, bean.user_id);
                        EventBus.getDefault().post(datamap);
                    }
                });
//                Map<String, Object> inParam = new HashMap<>();
//                inParam.put(EventBusConstant.TYPE, EventBusConstant.DELETE_FRIEND_PUSH);
//                inParam.put(EventBusConstant.DELETE_FRIEND_PUSH_BEAN, bean);
//                EventBus.getDefault().post(inParam);
    }

    private void parseInvite(JSONObject jsob) throws JSONException {
        JSONObject jsonPro = jsob.optJSONObject("pro_data");
        String jsonMsgBody = jsonPro.optString("msg_jsonbody");
        JSONObject jsonObject = new JSONObject(jsonMsgBody);
        final NewFriendBean bean = new NewFriendBean();
        bean.add_status = jsonObject.optInt("add_status");
        bean.user_id = jsonObject.optString("user_id"); //发送人的id
        bean.user_logo = jsonObject.optString("user_logo");
        bean.user_name = jsonObject.optString("user_name");
        bean.friend_id = jsonObject.optString("friend_id"); //要加的人的id,即本人id
        bean.friend_logo = jsonObject.optString("friend_logo");
        bean.friend_name = jsonObject.optString("friend_name");
        bean.req_desc = jsonObject.optString("req_desc");
        MyNewFriendDao.getInstance().insertOrUpdate(bean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Long>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Long aLong) {
                        if (aLong > 0) { //保存成功,推送事件
                            Map<String, Object> inParam = new HashMap<>();
                            inParam.put(EventBusConstant.TYPE, EventBusConstant.NEW_FRIEND_PUSH);
                            inParam.put(EventBusConstant.ACTION_KEY, EventBusConstant.NEW_FRIEND_PUSH_BEAN);
                            inParam.put(EventBusConstant.NEW_FRIEND_PUSH_BEAN, bean);
                            EventBus.getDefault().post(inParam);
                        }
                    }
                });
        //通知栏提醒等
        playSound(appContext); //播放提醒
//                Intent mIntent = new Intent(appContext, NewFriendActivity.class);
//                mIntent.putExtra(PersonCardActivity.FRIEND_ID, bean.user_id);
//                mIntent.putExtra(PersonCardActivity.ADD_FRIEND, true);
//                mIntent.putExtra(PersonCardActivity.ADD_FRIEND_DESC, bean.req_desc);
//                PackageManager packageManager = appContext.getPackageManager();
//                String appname = (String) packageManager.getApplicationLabel(appContext.getApplicationInfo());
//                // notification title
//                String contentTitle = appname;
//                // create and send notificaiton
//                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext)
//                        .setSmallIcon(appContext.getApplicationInfo().icon)
//                        .setWhen(System.currentTimeMillis())
//                        .setAutoCancel(true);
//                xmppNotifyID++;
//                PendingIntent pendingIntent = PendingIntent.getActivity(appContext, xmppNotifyID, mIntent,
//                        PendingIntent.FLAG_UPDATE_CURRENT);
//                String content = bean.user_name + "请求加您为好友 : " + bean.req_desc;
//                mBuilder.setContentTitle(contentTitle);
//                mBuilder.setTicker(content);
//                mBuilder.setContentText(content);
//                mBuilder.setContentIntent(pendingIntent);
//                // mBuilder.setNumber(notificationNum);
//                Notification notification = mBuilder.build();
//                notifyIdList.add(xmppNotifyID);
//                notificationManager.notify(xmppNotifyID, notification);
    }

    private void parseQacPush(JSONObject jsob) throws JSONException {
        JSONObject jsonPro = jsob.optJSONObject("pro_data");
        String msg_id = jsonPro.optString("msg_id");
        String msg_sequenceId = jsonPro.optString("msg_sequenceId");
        if (!TextUtils.isEmpty(msg_sequenceId) && !TextUtils.isEmpty(msg_id)) {
            sendReceipt(msg_id);
        }
        String jsonMsgBody = jsonPro.optString("msg_jsonbody");
        Map<String, Object> pushMap = new HashMap<>();
        pushMap.put(EventBusConstant.TYPE, EventBusConstant.QAC_CHAT);
        pushMap.put(EventBusConstant.ACTION_VALUE, jsonMsgBody);
        EventBus.getDefault().post(pushMap);
        //发送通知提醒
        Intent intent = new Intent();
        intent.putExtra("msg_jsonbody", jsonMsgBody);
        intent.setAction("cn.xspace.module.qac.receiver.HuanXinPushReceiver");//此处的名字要和接受者的一致
        appContext.sendBroadcast(intent);
        //下面是发送通知栏通知的方法
        String className = ClassUtil.QAC_CHAT_ACTIVITY;
        if (StringUtils.isNull(className)) {
            return;
        }
        JSONObject jsonObject = new JSONObject(jsonMsgBody);
        String qu_id_push = jsonObject.optString("qu_id");
        String msg_body = jsonObject.optString("tip_msg");
        String tip_msgid = jsonObject.optString("tip_msgid");
        Intent mIntent = new Intent(appContext, ClassUtil.getClassByName(className));
        mIntent.putExtra("qu_id", qu_id_push);
        mIntent.putExtra("tip_msgid", tip_msgid);
        playSound(appContext);
        sendNotification(msg_body, mIntent);
    }

    /**
     * 发送通知栏通知
     *
     * @param msg_body
     * @param mIntent
     */
    private void sendNotification(String msg_body, Intent mIntent) {
        if (!ImPreferences.getInstance(appContext).getPfBoolean(AppUtils.isNotifyOpen)) {
            return;
        }
        PackageManager packageManager = appContext.getPackageManager();
        String appName = (String) packageManager.getApplicationLabel(appContext.getApplicationInfo());
        // notification title
        // create and send notificaiton
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext)
                .setSmallIcon(appContext.getApplicationInfo().icon)
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true);
        xmppNotifyID++;
        PendingIntent pendingIntent = PendingIntent.getActivity(appContext, xmppNotifyID, mIntent, PendingIntent
                .FLAG_UPDATE_CURRENT);
        mBuilder.setContentTitle(appName);
        mBuilder.setTicker(msg_body);
        mBuilder.setContentText(msg_body);
        mBuilder.setContentIntent(pendingIntent);
        // mBuilder.setNumber(notificationNum);
        Notification notification = mBuilder.build();
        notifyIdList.add(xmppNotifyID);
        notificationManager.notify(xmppNotifyID, notification);
    }

    private void sendReceipt(String msg_id) {
        //发送回执
        HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_id", user_id);
        requestMap.put("msg_id", msg_id);
        OkHttpManager.getInstance().commonRequest(Constants.UPDATE_MSG_STATE, requestMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                    }
                });
    }

    private int playSound(Context appContext) {

        if (System.currentTimeMillis() - lastNotifiyTime < 1000) {
            // received new messages within 1 seconds, skip play ringtone
            return 0;
        }
        lastNotifiyTime = System.currentTimeMillis();

        NotificationManager mgr = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification nt = new Notification();
        Uri alert = null;
        try {
            if (ImPreferences.getInstance(appContext).getPfBoolean(AppUtils.isNotifyAlert)) {
                alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            }
        } catch (Exception e) {
            alert = null;
        }
        if (ImPreferences.getInstance(appContext).getPfBoolean(AppUtils.isNotifyvibation)) {
            nt.defaults = Notification.DEFAULT_VIBRATE;// 设置默认震动
        }
        if (alert != null) {
            nt.sound = alert;
        }
        int soundId = new Random(System.currentTimeMillis()).nextInt(Integer.MAX_VALUE);
        mgr.notify(soundId, nt);
        return soundId;
    }

    MessageEntity listEntity = null;
    MsgRecordEntity recordEntity = null;
    /**
     * 某些系统提示消息需要分成两条保存到数据库中，
     * 比如 邀请好友 ，若你在其中需要显示你被邀请的提示
     */

    MsgRecordEntity recordSystemEntity = null;

    /**
     * 判断是否为自己发送的
     *
     * @param userId
     * @return
     */
    private boolean isYouSend(String userId) {
        if (userId.equals(user_id)) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否为临时会话
     *
     * @param msg_org
     * @return
     */
    private boolean isTempConversation(int msg_org) {
        if (msg_org == Type.GroupType.TEMP_GROUP) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 解析群聊
     *
     * @param message
     */

    public void parseChatGroup(EMMessage message) {
        EMMessageBody body = message.getBody();
        String bodyStr = body.toString();
        LogUtil.d(TAG, "body str " + bodyStr);
        String jsondata = "";
        listEntity = new MessageEntity();
        recordEntity = new MsgRecordEntity();
        recordSystemEntity = new MsgRecordEntity();
        if (bodyStr.indexOf("txt:") == 0) {
            jsondata = bodyStr.substring(5);
            jsondata = jsondata.substring(0, jsondata.lastIndexOf("\""));
        }
        JSONObject jsob;
        try {
            jsob = new JSONObject(jsondata);
            //区分推送平台
            String platForm = jsob.optString("plat_form");
            //区分单聊还是推送push
            String msg_plat = jsob.optString("msg_plat");
            if ("WNXWEB".equals(platForm)) {
                if ("wnx_chat_group".equals(msg_plat)) {
                    parseWnxChatGroup(jsob);
                }
            } else if ("QACWEB".equals(platForm)) { //农技员推送
                if ("qac_chat_group".equals(msg_plat)) {
                    parseQacChatGroup(jsob);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void parseWnxChatGroup(JSONObject jsobPre) throws JSONException {
        JSONObject jsonPro = jsobPre.optJSONObject("pro_data");
        String jsonMsgBody = jsonPro.optString("msg_jsonbody");
        JSONObject jsob = new JSONObject(jsonMsgBody);
        //发送人发送人id
        String msg_sender_id = jsob.optString("msg_sender_id");
        LogUtil.d("msg_sender_id>>" + msg_sender_id);
        //群组Id
        String group_id = jsob.optString("group_id");
        //发送人logo
        String msg_sender_logo = jsob.optString("msg_sender_logo");
        //发送人name
        String msg_sender_name = jsob.optString("msg_sender_name");
        //群组名称
        String group_name = jsob.optString("group_name");
        //群组logo
        String group_logo = jsob.optString("group_logo");
        //消息Id
        String msg_id = jsob.optString("msg_id");
        //操作类型
        int tip_type = jsob.optInt("tip_type");
        //发送内容描述
        String msg_txt = jsob.optString("msg_text");
        //内容类型
        int msg_type = jsob.optInt("msg_type");
        //群组类型
        int msg_org = jsob.optInt("msg_org");
        if (msg_org == Type.GroupType.QAC) {
            //农技员群聊推送
            String userId = jsob.optString("user_id");
            String senderId = jsob.optString("msg_sender_id");
            if (user_id.equals(userId)) { //沃基己发的
                return;
            }
            if (user_id.equals(senderId)) {
                return;
            }
            if (tip_type == 1) {
                //转呈添加人员
                msg_txt = "您有问题需要会商";
            }
            Map<String, Object> pushMap = new HashMap<>();
            pushMap.put(EventBusConstant.TYPE, EventBusConstant.QAC_CHAT_TRANSFER);
            pushMap.put(EventBusConstant.ACTION_VALUE, jsob);
            EventBus.getDefault().post(pushMap);

            String className = ClassUtil.QAC_CHAT_ACTIVITY;
            if (StringUtils.isNull(className)) {
                return;
            }
            String qu_id_push = jsob.optString("qu_id");
            Intent mIntent = new Intent(appContext, ClassUtil.getClassByName(className));
            mIntent.putExtra("qu_id", qu_id_push);
            mIntent.putExtra("group_id", group_id);
            mIntent.putExtra(Constants.QUESTION_TYPE, Constants.TRANSFER);
            playSound(appContext);
            PackageManager packageManager = appContext.getPackageManager();
            String appname = (String) packageManager.getApplicationLabel(appContext.getApplicationInfo());
            // notification title
            // create and send notificaiton
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext)
                    .setSmallIcon(appContext.getApplicationInfo().icon)
                    .setWhen(System.currentTimeMillis())
                    .setAutoCancel(true);
            PendingIntent pendingIntent = PendingIntent.getActivity(appContext, notifyID, mIntent, PendingIntent
                    .FLAG_UPDATE_CURRENT);
            mBuilder.setContentTitle(appname);
            mBuilder.setTicker(msg_txt);
            mBuilder.setContentText(msg_txt);
            mBuilder.setContentIntent(pendingIntent);
            // mBuilder.setNumber(notificationNum);
            Notification notification = mBuilder.build();
            xmppNotifyID++;
            notifyIdList.add(xmppNotifyID);
            notificationManager.notify(xmppNotifyID, notification);
            return;
        }
        //发送时间
        String msg_time = jsob.optString("msg_time");
        String inserttime = String.valueOf(System.currentTimeMillis());
        //得到消息描述文字
        String showContent = ChatFileEntity.getContentByType(msg_txt, msg_type, msg_sender_name);
        listEntity.msg_content_type = msg_type;
        //系统提示
        LogUtil.e(TAG, "wubaojie>>>" + "消息描述文字: showContent:" + showContent);
        if (msg_type == ContentType.SYSTEM_WARN.toNumber()) {
            boolean isFirstCreate = false;
            if (tip_type == MessageEntity.SystemType.Invite.toNumber()) {
                //邀请
                JSONArray userArray = jsob.getJSONArray("userList");
                StringBuffer msgContentSb = new StringBuffer();
                StringBuffer allUserNameSb = new StringBuffer();
                for (int i = 0; i < userArray.length(); i++) {
                    JSONObject userJson = userArray.optJSONObject(i);
                    String userId = userJson.optString(RequestConstant.KEY_USER_ID);
                    String userName = userJson.optString(RequestConstant.KEY_USER_NAME);
                    allUserNameSb.append(userName + "、");

                    if (isYouSend(msg_sender_id)) {
                        ////你邀请。。。加入群组,
                        if (user_id.equals(userId)) {
                            //把自己排除在外
                            if (msg_sender_id.equals(userId)) {
                                isFirstCreate = true;
//                                    isNeedSaveTwoMsg = true;
                            }
                        } else {
                            msgContentSb.append(userName + "、");
                        }
                    } else {
                        //不是我自己发送的，谁邀请谁谁加入群组，同样也要把群主剔除
                        if (user_id.equals(userId)) {
                            isYouAreInvited = true;
                            //我被邀请了， 你加入了会话
//                                isNeedSaveTwoMsg = true;
                        } else if (msg_sender_id.equals(userId)) {
                            isFirstCreate = true;
                        } else {
                            msgContentSb.append(userName + "、");
                        }
                    }

                }
                if (allUserNameSb.lastIndexOf("、") != -1) {
                    allUserNameSb.deleteCharAt(allUserNameSb.lastIndexOf("、"));
                }
                if (isFirstCreate) {
                    //群组没有名称的时候显示所有用户的名称,第一次创建
                    if (TextUtils.isEmpty(listEntity.msg_group_name)) {
                        listEntity.msg_group_name = allUserNameSb.toString();
                    }
                } else {
                    listEntity.msg_group_name = group_name;
                }

                //XXX邀请XXX、XXX加入了群组  xxx、xxx 加入了会话
                if (msgContentSb.lastIndexOf("、") != -1) {
                    msgContentSb.deleteCharAt(msgContentSb.lastIndexOf("、"));
                }

                if (isYouSend(msg_sender_id)) {
                    //创建人收到的系统提示，有两个提醒 你创建了一个会话  ，谁谁谁加入了会话
                    if (isFirstCreate) {
                        recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                                .you_create_a_conversation));

                        //创建会话的时候，不显示  谁谁加入会话
                       /*     if (!TextUtils.isEmpty(msgContentSb.toString())) {
                                //谁谁谁加入了会话
                                if (isTempConversation(msg_org)) {
                                    recordSystemEntity.msg_content = String.format(appContext.getResources()
                                    .getString(R.string
                                            .who_add_conversation), msgContentSb.toString());
                                } else {
                                    recordSystemEntity.msg_content = String.format(appContext.getResources()
                                    .getString(R.string
                                            .who_add_group), msgContentSb.toString());
                                }
                                recordSystemEntity.msg_group_id = group_id;
                                recordSystemEntity.msg_id = System.currentTimeMillis() + "System";
                                recordSystemEntity.inserttime = inserttime;
                                recordSystemEntity.tip_type = tip_type;
                                recordSystemEntity.msg_last_time = msg_time;
                                recordSystemEntity.msg_type = MessageEntity.MsgType.CHAT_CROUP.toNumber();
                                recordSystemEntity.msg_content_type = msg_type;
//                            recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
//                                    .you_invite_who_to_group), msgContentSb.toString());
                            }*/
                    } else {
                        if (!TextUtils.isEmpty(msgContentSb.toString())) {
                            //谁谁谁加入了会话
                            if (isTempConversation(msg_org)) {
                                recordEntity.msg_content = String.format(appContext.getResources().getString(R
                                        .string
                                        .who_add_conversation), msgContentSb.toString());
                            } else {
                                recordEntity.msg_content = String.format(appContext.getResources().getString(R
                                        .string
                                        .who_add_group), msgContentSb.toString());
                            }
                        } else {
                            LogUtil.d("msgContentSb.toString == null");
                        }
                    }
//                        isNeedNotice = false;
                } else if (isYouAreInvited) {

                    //你被邀请加入群组
                    if (isTempConversation(msg_org)) {
                        //你加入了会话
                        recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                                .who_add_conversation), appContext.getResources().getString(R.string
                                .you));
                        if (isFirstCreate) {
                            listEntity.isShow = 0;
                        }
                    } else {
                        //你加入了群组
                        recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                                .who_add_group), appContext.getResources().getString(R.string
                                .you));
                        if (isFirstCreate) {
                            listEntity.isShow = 0;
                        }
                    }
                    isYouAreInvited = false;
                } else {
                    if (!TextUtils.isEmpty(msgContentSb.toString())) {
                        //XX加入会话
                        if (isTempConversation(msg_org)) {
                            //你加入了会话
                            recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                                    .who_add_conversation), msgContentSb.toString());
                            if (isFirstCreate) {
                                listEntity.isShow = 0;
                            }

                        } else {
                            //XX加入了群组
                            recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                                    .who_add_group), msgContentSb.toString());
                            if (isFirstCreate) {
                                listEntity.isShow = 0;
                            }
                        }
                    } else {
                        LogUtil.d("msgContentSb.toString == null");
                    }

                }
//                    else if (!TextUtils.isEmpty(msgContentSb.toString())) {
//                        //不是我发送的，且
//                        recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
//                                .who_invite_whos_to_group), msg_sender_name, msgContentSb.toString());
//                        if (isNeedSaveTwoMsg) {
//                            recordSystemEntity.msg_content =
//                                    String.format(appContext.getResources().getString(R.string
//                                            .who_invite_you_to_group), msg_sender_name);
//                            recordSystemEntity.msg_group_id = group_id;
//                            recordSystemEntity.msg_id = msg_id;
//                            recordSystemEntity.inserttime = inserttime;
//                            recordSystemEntity.tip_type = tip_type;
//                            recordSystemEntity.msg_last_time = msg_time;
//                            recordSystemEntity.msg_type = MessageEntity.MsgType.CHAT_CROUP.toNumber();
//                            recordSystemEntity.msg_content_type = msg_type;
////                            recordSystemEntity.msg_group_name = group_name;
//                        }
//                    } else if (isNeedSaveTwoMsg) {
//                        //只邀请了一个人，且为自己
//                        isInviteYouOnly = true;
//                        recordEntity.msg_content =
//                                String.format(appContext.getResources().getString(R.string.who_invite_you_to_group),
//                                        msg_sender_name);
//                        recordEntity.msg_group_id = group_id;
//                        recordEntity.msg_id = msg_id;
//                        recordEntity.inserttime = inserttime;
//                        recordEntity.tip_type = tip_type;
//                        recordEntity.msg_last_time = msg_time;
//                        recordEntity.msg_type = MessageEntity.MsgType.CHAT_CROUP.toNumber();
//                        recordEntity.msg_content_type = msg_type;
////                        recordEntity.msg_group_name = group_name;
//                    }
            } else if (tip_type == MessageEntity.SystemType.GroupOwnerChange.toNumber()) {
                //群主更改  XXX成为新群主
                //接受者Id
                String msg_recevier_id = jsob.optString("msg_recevier_id");
                String msg_recevier_name = "";
                if (user_id.equals(msg_recevier_id)) {
                    msg_recevier_name = appContext.getResources().getString(R.string.you);
                } else {
                    msg_recevier_name = jsob.optString("msg_recevier_name");
                }
                recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                        .who_become_new_group_owner), msg_recevier_name);
            } else if (tip_type == MessageEntity.SystemType.GroupRemoveMember.toNumber()) {
                //群主移除成员
                JSONArray userArray = jsob.getJSONArray("userList");
                StringBuffer msgContentSb = new StringBuffer();
                boolean isMine = false;
                for (int i = 0; i < userArray.length(); i++) {
                    JSONObject userJson = userArray.optJSONObject(i);
                    String userId = userJson.optString(RequestConstant.KEY_USER_ID);
                    String userName = userJson.optString(RequestConstant.KEY_USER_NAME);
                    LogUtil.d(TAG, "wubaojie>>>parseChatGroup: userId:" + userId + " user_id:" + user_id);
                    if (user_id.equals(userId)) {
//                            isNeedSaveTwoMsg = true;
                        isMine = true;
                        //你已被移出了群组
                        if (isTempConversation(msg_org)) {
                            recordEntity.msg_content = appContext.getString(R.string.you_removed_from_conversation);
                        } else {
                            recordEntity.msg_content = appContext.getString(R.string.you_removed_from_group);
                        }
                        HashMap<String, Object> map = new HashMap<>();
                        map.put(EventBusConstant.TYPE, EventBusConstant.HUANXIN_PUSH); //移出群组
                        map.put(EventBusConstant.HUANXIN_PUSH_BEAN, EventBusConstant.SHIFT_OUT_GROUP);
                        EventBus.getDefault().post(map);
//                                    appContext.getResources().getString(R.string.you_removed_from_group);
                        break;
                    } else {
                        msgContentSb.append(userName + "、");
                    }
                }
                if (!isMine) {
                    //XXX将XXX、XXX移出了群组   XXX 退出了会话/群组 我不包括在内
                    if (msgContentSb.lastIndexOf("、") != -1) {
                        msgContentSb.deleteCharAt(msgContentSb.lastIndexOf("、"));
                    }
                    if (isTempConversation(msg_org)) {
                        recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                                .who_exit_from_conversation), msgContentSb.toString());
                    } else {
                        recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                                .who_exit_from_group), msgContentSb.toString());
                    }
                }
//                    if (isYouSend(msg_sender_id)) {
//                        recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
//                                        .who_remove_who_from_group),
//                                appContext.getResources().getString(R.string.you), msgContentSb.toString());
//                    } else {
//                        if (!isMine) { //前面已经判断过了,你被提出群组,这里就不用走了
//                            recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
//                                    .who_remove_who_from_group), msg_sender_name, msgContentSb.toString());
//                        }
//                    }

            } else if (tip_type == MessageEntity.SystemType.GroupNameChange.toNumber()) {
                //修改群名称
                if (isTempConversation(msg_org)) {
                    recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                                    .conversation_name_change_what),
                            group_name);
                } else {
                    recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                                    .group_name_change_what),
                            group_name);
                }

//                    if (isYouSend(msg_sender_id)) {
//                        recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
//                                        .who_update_group_name),
//                                appContext.getResources().getString(R.string.you), group_name);
//                    } else {
//                        recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
//                                .who_update_group_name), msg_sender_name, group_name);
//                    }
                recordEntity.msg_group_name = group_name;
                listEntity.msg_group_name = group_name;
            } else if (tip_type == MessageEntity.SystemType.WithDraw.toNumber()) {
                //撤销消息
                //见saveDb方法，跟单聊同样处理
                if (isYouSend(msg_sender_id)) {
                    recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                                    .who_withdraw_a_message),
                            appContext.getResources().getString(R.string.you));
                } else {
                    recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                            .who_withdraw_a_message), msg_sender_name);
                }
                showContent = recordEntity.msg_content;
            } else if (tip_type == MessageEntity.SystemType.MemberExit.toNumber()) {
                //成员退出
                //发送人是自己取消
                LogUtil.d(TAG, "wubaojie>>>成员退出:" + msg_sender_name);
                if (isYouSend(msg_sender_id)) {
                    return;
                }
                //成员主动退出
                if (isTempConversation(msg_org)) {
                    //谁退出了会话
                    recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                            .who_exit_from_conversation), msg_sender_name);
                } else {
                    //谁退出了群组
                    recordEntity.msg_content = String.format(appContext.getResources().getString(R.string
                            .who_exit_from_group), msg_sender_name);
                }
            }
            recordEntity.tip_type = tip_type;
            listEntity.tip_type = tip_type;
        } else {
            LogUtil.d("正常消息 user_id>>" + user_id);
            LogUtil.d("正常消息 sender_id>>" + msg_sender_id);
            //自己发送的不接受群聊推送
            if (msg_sender_id.equals(user_id)) {
                LogUtil.d("自己发送的");
                return;
            }

            if (ChatFileEntity.isNeedSaveFile(msg_type)) {
                //带有附件的消息
                ChatFileEntity fileEntity = new ChatFileEntity();
                //文件实体类url
//                    fileEntity.msg_id = msg_id;
                fileEntity.file_url_remote = msg_txt;
                fileEntity.file_type = msg_type;
                if (msg_type == ContentType.VOICE.toNumber()) {
                    int msg_dutime = jsob.optInt("msg_dutime");
                    fileEntity.msg_dutime = msg_dutime;
                } else if (msg_type == ContentType.LOCATION.toNumber()) {
                    fileEntity.address_desc = jsob.optString("msg_postion");
                    fileEntity.lat = jsob.optString("msg_lat");
                    fileEntity.lng = jsob.optString("msg_lng");
                } else if (msg_type == ContentType.FILE.toNumber()) {
                    fileEntity.file_name = jsob.optString("msg_name");
                }
                recordEntity.mFileEntity = fileEntity;
            } else {
                //普通消息
                recordEntity.msg_content = msg_txt;
            }
        }
        listEntity.msg_content = showContent;
        //非操作消息
        recordEntity.msg_group_name = group_name;
        listEntity.msg_group_name = group_name;
        recordEntity.group_type = msg_org;
        listEntity.group_type = msg_org;
        //聊天记录beana操作
        if (TextUtils.isEmpty(msg_id)) {
            recordEntity.msg_id = System.currentTimeMillis() + "";
        } else {
            recordEntity.msg_id = msg_id;
        }

        recordEntity.msg_group_id = group_id;
        listEntity.msg_group_id = group_id;
        recordEntity.msg_sender_id = msg_sender_id;
        listEntity.msg_sender_id = msg_sender_id;
        recordEntity.inserttime = inserttime;
        listEntity.inserttime = inserttime;
        recordEntity.msg_sender_name = msg_sender_name;
        listEntity.msg_sender_name = msg_sender_name;
        recordEntity.msg_logo = msg_sender_logo;
        listEntity.msg_logo = group_logo;
        recordEntity.msg_content_type = msg_type;
        listEntity.msg_content_type = msg_type;
        recordEntity.msg_last_time = msg_time;
        listEntity.msg_last_time = msg_time;

        recordEntity.msg_type = MsgType.CHAT_CROUP.toNumber();
        listEntity.msg_type = MsgType.CHAT_CROUP.toNumber();
        //给列表赋值
        LogUtil.d(TAG, "enrity " + listEntity.toString());
        LogUtil.d(TAG, "recordEntity " + recordEntity.toString());
        LogUtil.d(TAG, "recordSystemEntity " + recordSystemEntity.toString());

        saveDb();
        dealHuanxinNotice();
    }

    public void reset() {
        resetNotificationCount();
        cancelNotificaton();
    }

    void resetNotificationCount() {
        notificationNum = 0;
        fromUsers.clear();
    }

    void cancelNotificaton() {
        if (notificationManager != null) {
            notificationManager.cancel(notifyID);
        }
//        cancelQacNotifacation();
    }

    public void cancelQacNotifacation() {
        for (Integer notifyId : notifyIdList) {
            notificationManager.cancel(notifyId);
        }
        notifyIdList.clear();
    }

    public interface EaseNotificationInfoProvider {
        /**
         * set the notification content, such as "you received a new image from xxx"
         *
         * @param message
         * @return null-will use the default text
         */
        String getDisplayedText(MessageEntity message);

        /**
         * set the notification content: such as "you received 5 message from 2 contacts"
         *
         * @param message
         * @param fromUsersNum- number of message sender
         * @param messageNum    -number of messages
         * @return null-will use the default text
         */
        String getLatestText(MessageEntity message, int fromUsersNum, int messageNum);

        /**
         * 设置notification标题
         *
         * @param message
         * @return null- will use the default text
         */
        String getTitle(MessageEntity message);

        /**
         * set the small icon
         *
         * @param message
         * @return 0- will use the default icon
         */
        int getSmallIcon(MessageEntity message);

        /**
         * set the intent when notification is pressed
         *
         * @param message
         * @return null- will use the default icon
         */
        Intent getLaunchIntent(MessageEntity message);
    }
}
